package com.tyut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyut.config.UserException;
import com.tyut.entity.Address;
import com.tyut.entity.Merchant;
import com.tyut.mapper.MerchantMapper;
import com.tyut.service.AddressService;
import com.tyut.service.FilesService;
import com.tyut.service.MerchantService;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 商家表 服务实现类
 * </p>
 *
 * @author 山田凉
 * @since 2025-03-18
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Resource
    AddressService addressService;

    @Resource
    FilesService filesService;

    @Override
    public boolean applyForMerchant(Merchant merchant, Address address, MultipartFile merPicture, MultipartFile merCheckPhoto) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        QueryWrapper<Merchant> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", merchant.getUserId());
        // 判断用户是否已经申请过商家
        if (this.getOne(wrapper) != null) {
            throw new UserException("您已经申请过商家了");
        }
        // 设置商家信息
        // 设置商家封面，与商家营业执照图片
        merchant.setPicture(filesService.fileUpload("gaming",merPicture,0L , "default"));
        merchant.setPhoto(filesService.fileUpload("gaming",merCheckPhoto,0L , "default"));
        // 设置商家地址
        merchant.setLocation(addressService.setAddress(address));

        return this.save(merchant);
    }

    @Override
    public boolean checkApply(Integer id) {
        QueryWrapper<Merchant> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        return this.getOne(wrapper) == null;
    }

}
